package v1

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"github.com/gorilla/websocket"
	"go.uber.org/zap"
	"mycms/global"
	"mycms/model/common"
	"mycms/model/common/response"
	"net/http"
)

// 保存历史消息的条数
const ArchiveSize = 20
const ChanSize = 10

var upGrader = websocket.Upgrader{
	// 解决跨域问题
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}



func Ping(c *gin.Context)  {

	ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}



	go testRead(ws)

}

func testRead(ws *websocket.Conn)  {
	defer ws.Close()
	for  {
		mt, message, err := ws.ReadMessage()
		println(message)
		if err != nil {
			//	有错误，写日志
			global.LOG.Error("WebSocket错误：", zap.Error(err))
			break
		}

		if string(message) == "ping" {
			message = []byte("pong")
		}
		json.Unmarshal(message, &common.ClientMsg)
		println(common.ClientMsg.Msg)
		println(common.ClientMsg.Data)
		// 向客户端写入数据
		err = ws.WriteMessage(mt, message)

		if err != nil {
			//	写入失败
			break
		}


	}
}

//	创建聊天室
func CreateRoom(c *gin.Context) {
	r := &common.Room{
		Users: map[common.Uid]common.Client{},
		UserCount: 0,
		EventChn: make(chan common.Event, ChanSize),
		JoinChn: make(chan common.Client, ChanSize),
		LeaveChn: make(chan common.Uid, ChanSize),
	}

	uid := "room_"+uuid.New().String()	//	生成uid

	common.RoomsList[uid] = *r

	go r.Serve()
	type romm struct {
		Id string
	}

	//	返回聊天室ID
	response.OkWithDetailed(romm{Id: uid},"创建成功", c)
}


//	websocket处理函数
func Handle(c *gin.Context)  {
	user_id := c.Query("uid")
	Username := c.Query("username")

	println(Username)
	println("用戶進入")

	conn, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}


	// 创建一个用户实例
	client := &common.Client{
		Conn: conn,
		RemoteAddr: conn.RemoteAddr().String(),
		Uid: user_id,
		Username: Username,
		UserEventChn: make(chan common.Event, ChanSize), //	通道要先make一下才能使用
	}


	go client.Read(common.ClientMsg, common.RoomsList)
	go client.Write()

	// 用户注册到用户管理上
	//system.Manager.Register <- client

}
